package com.atguigu.medical.realtime.sink;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.medical.realtime.bean.TableProcess;
import com.atguigu.medical.realtime.util.DimUtil;
import com.atguigu.medical.realtime.util.JdbcUtil;
import com.atguigu.medical.realtime.util.RedisUtil;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.functions.sink.RichSinkFunction;
import redis.clients.jedis.Jedis;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @Author lzc
 * @Date 2023/4/22 09:24
 */
public class PhoenixSink extends RichSinkFunction<Tuple2<JSONObject, TableProcess>> {
    
    private Connection conn;
    private Jedis redisClient;
    
    @Override
    public void open(Configuration parameters) throws Exception {
        conn = JdbcUtil.getPhoenixConnection();  // alt+ctrl+f 提升为成员变量
        
        redisClient = RedisUtil.getRedisClient();
        
    }
    
    @Override
    public void close() throws Exception {
        JdbcUtil.closeConnection(conn);
        
        redisClient.close();
        
    }
    
    @Override
    public void invoke(Tuple2<JSONObject, TableProcess> t, Context context) throws Exception {
        JSONObject data = t.f0;
        TableProcess tp = t.f1;
        
      
        String opType = data.getString("op_type");
        
        // 使用 jdbc 连接 phoenix, 写入
        upsert(data, tp);
        
        // 删除缓存
        if( "u".equals(opType)){
            delRedisCache(data, tp);
        }
    }
    
    private void delRedisCache(JSONObject data, TableProcess tp) {
        String key = DimUtil.getKey(tp.getSinkTable(), data.getString("id"));
        if (redisClient.del(key) == 0) {
            System.out.println(key + " 删除失败...");
        }else{
            System.out.println(key + " 删除成功...");
        }
    }
    
    private void upsert(JSONObject data, TableProcess tp) throws SQLException {
        StringBuilder sql = new StringBuilder(); // TODO 拼接 sql
        sql
            .append("upsert into ")
            .append(tp.getSinkTable())
            .append("(")
            .append(tp.getSinkColumns())
            .append(")values(")
            .append(tp.getSinkColumns().replaceAll("[^,]+", "?"))
            .append(")");
        System.out.println("phoenix 的插入语句: " + sql);
        // 1. 获取一个预处理语句
        PreparedStatement ps = conn.prepareStatement(sql.toString());
        // 2. 给 sql 中的占位符进行赋值  TODO
        String[] columns = tp.getSinkColumns().split(",");
        for (int i = 0; i < columns.length; i++) {
            String column = columns[i];
            String v = data.getString(column);  // 根据列名, 获取对应的值
            ps.setString(i + 1, v);  // 给占位符进行赋值: 索引是从 1 开始
        }
        // 3. 执行预处理语句
        ps.execute();
        // 4. 提交(如果是插入语句需要 commit, 因为 phoenix 没有自动提交)
        conn.commit();
        // 5. 关闭预处理
        ps.close();
    }
}
